﻿using ERPWinFormWork.Material.Material.Dtos;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERPWinFormWork.Material
{
    public partial class AddMaterial : Form
    {
        public string SelectedMaterialNumber { get; private set; }
        public string SelectedMaterialName { get; private set; }
        public string SelectedSpecifications { get; private set; }
        public string SelectedUnitName { get; private set; }
        
        /// <summary>
        /// 获取选中的物料项目列表
        /// </summary>
        /// <returns>选中的物料项目列表</returns>
        public List<Material_TableOutput> GetSelectedItems()
        {
            var selectedItems = new List<Material_TableOutput>();
            
            for (int i = 0; i < dgvmaterial.Rows.Count; i++)
            {
                DataGridViewCheckBoxCell checkBoxCell = dgvmaterial.Rows[i].Cells[0] as DataGridViewCheckBoxCell;
                if (checkBoxCell != null && checkBoxCell.Value != null && (bool)checkBoxCell.Value)
                {
                    // 获取选中行的数据
                    var materialOutput = new Material_TableOutput
                    {
                        Id = Convert.ToInt32(dgvmaterial.Rows[i].Cells[1].Value ?? 0), // 物料ID
                        MaterialNumber = dgvmaterial.Rows[i].Cells[2].Value?.ToString() ?? "", // 物料编号
                        MaterialName = dgvmaterial.Rows[i].Cells[3].Value?.ToString() ?? "", // 物料名称
                        Specifications = dgvmaterial.Rows[i].Cells[4].Value?.ToString() ?? "", // 规格型号
                        Unit_Id = Convert.ToInt32(dgvmaterial.Rows[i].Cells[5].Value ?? 0), // 单位ID
                        Unit_Name = dgvmaterial.Rows[i].Cells[6].Value?.ToString() ?? "" // 单位名称
                    };
                    
                    selectedItems.Add(materialOutput);
                }
            }
            
            return selectedItems;
        }

        public AddMaterial()
        {
            InitializeComponent();
            _apiClient = new ApiClient(MaterialAppConfig.ApiBaseUrl);
            InitializeDataGridView();
            GetData();
            LoadunitData();

            // 绑定按钮事件
            btnsure5.Click += Btnsure5_Click;
            btnquxiao5.Click += Btnquxiao5_Click;
            
            // 设置窗体标题
            this.Text = "选择物料";
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            
            // 设置按钮提示文本
            if (btnsure5 != null)
                btnsure5.Text = "确定选择";
            if (btnquxiao5 != null)
                btnquxiao5.Text = "取消";
            
            // 添加键盘事件
            this.KeyPreview = true;
            this.KeyDown += AddMaterial_KeyDown;

            tbxwuliaoname.Text = string.Empty;
            tbxwuliaoname.WaterText = "请输入物料名称";
            tbxwuliaoname.SkinTxt.Text = string.Empty;
            tbxwuliaoname.SkinTxt.WaterText = "请输入物料名称";


            
        }

        /// <summary>
        /// 确定按钮点击事件
        /// </summary>
        private void Btnsure5_Click(object sender, EventArgs e)
        {
            // 查找选中的行
            for (int i = 0; i < dgvmaterial.Rows.Count; i++)
            {
                DataGridViewCheckBoxCell checkBoxCell = dgvmaterial.Rows[i].Cells[0] as DataGridViewCheckBoxCell;
                if (checkBoxCell != null && checkBoxCell.Value != null && (bool)checkBoxCell.Value)
                {
                    // 获取选中行的数据
                    SelectedMaterialNumber = dgvmaterial.Rows[i].Cells[2].Value?.ToString() ?? ""; // 物料编号
                    SelectedMaterialName = dgvmaterial.Rows[i].Cells[3].Value?.ToString() ?? ""; // 物料名称
                    SelectedSpecifications = dgvmaterial.Rows[i].Cells[4].Value?.ToString() ?? ""; // 规格型号
                    SelectedUnitName = dgvmaterial.Rows[i].Cells[6].Value?.ToString() ?? ""; // 单位名称
                    
                    // 调试信息：显示获取到的数据
                    Console.WriteLine($"选中的物料信息:");
                    Console.WriteLine($"  物料编号: {SelectedMaterialNumber}");
                    Console.WriteLine($"  物料名称: {SelectedMaterialName}");
                    Console.WriteLine($"  规格型号: {SelectedSpecifications}");
                    Console.WriteLine($"  单位名称: {SelectedUnitName}");
                    
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                    return;
                }
            }
            
            MessageBox.Show("请先选择一条记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        
        /// <summary>
        /// 搜索物料
        /// </summary>
        /// <param name="searchText">搜索文本</param>
        public void SearchMaterial(string searchText)
        {
            if (!string.IsNullOrWhiteSpace(searchText))
            {
                var searchParams = new Dictionary<string, string>
                {
                    { "materialName", searchText }
                };
                GetData(searchParams);
            }
            else
            {
                GetData(); // 清空搜索条件，显示所有数据
            }
        }
        
        /// <summary>
        /// 显示使用提示
        /// </summary>
        private void ShowUsageTip()
        {
            string tip = "使用说明：\n" +
                        "1. 点击复选框选择物料\n" +
                        "2. 双击行可快速选择\n" +
                        "3. 点击确定按钮完成选择\n" +
                        "4. 点击取消按钮关闭窗口\n" +
                        "5. 按F1键查看此帮助";
            
            MessageBox.Show(tip, "使用提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        
        /// <summary>
        /// 键盘事件处理
        /// </summary>
        private void AddMaterial_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F1:
                    ShowUsageTip();
                    break;
                case Keys.Enter:
                    // 按回车键确认选择
                    Btnsure5_Click(sender, e);
                    break;
                case Keys.Escape:
                    // 按ESC键取消
                    Btnquxiao5_Click(sender, e);
                    break;
            }
        }
        
        /// <summary>
        /// 更新状态栏显示选中的物料信息
        /// </summary>
        private void UpdateStatusBar()
        {
            for (int i = 0; i < dgvmaterial.Rows.Count; i++)
            {
                DataGridViewCheckBoxCell checkBoxCell = dgvmaterial.Rows[i].Cells[0] as DataGridViewCheckBoxCell;
                if (checkBoxCell != null && checkBoxCell.Value != null && (bool)checkBoxCell.Value)
                {
                    string materialNumber = dgvmaterial.Rows[i].Cells[2].Value?.ToString() ?? "";
                    string materialName = dgvmaterial.Rows[i].Cells[3].Value?.ToString() ?? "";
                    string specifications = dgvmaterial.Rows[i].Cells[4].Value?.ToString() ?? "";
                    string unitName = dgvmaterial.Rows[i].Cells[6].Value?.ToString() ?? "";
                    
                    string statusText = $"已选择: {materialName} ({materialNumber}) - {specifications} - {unitName}";
                    this.Text = $"选择物料 - {statusText}";
                    return;
                }
            }
            
            // 没有选中任何物料时，恢复默认标题
            this.Text = "选择物料";
        }
        
        /// <summary>
        /// 添加右键菜单
        /// </summary>
        private void AddContextMenu()
        {
            ContextMenuStrip contextMenu = new ContextMenuStrip();
            
            // 选择物料菜单项
            ToolStripMenuItem selectItem = new ToolStripMenuItem("选择此物料");
            selectItem.Click += (sender, e) => {
                if (dgvmaterial.CurrentRow != null)
                {
                    int rowIndex = dgvmaterial.CurrentRow.Index;
                    // 选中当前行
                    for (int i = 0; i < dgvmaterial.Rows.Count; i++)
                    {
                        dgvmaterial.Rows[i].Cells[0].Value = (i == rowIndex);
                    }
                    UpdateStatusBar();
                }
            };
            contextMenu.Items.Add(selectItem);
            
            // 分隔线
            contextMenu.Items.Add(new ToolStripSeparator());
            
            // 查看详情菜单项
            ToolStripMenuItem detailsItem = new ToolStripMenuItem("查看物料详情");
            detailsItem.Click += (sender, e) => {
                if (dgvmaterial.CurrentRow != null)
                {
                    int rowIndex = dgvmaterial.CurrentRow.Index;
                    string materialNumber = dgvmaterial.Rows[rowIndex].Cells[2].Value?.ToString() ?? "";
                    string materialName = dgvmaterial.Rows[rowIndex].Cells[3].Value?.ToString() ?? "";
                    string specifications = dgvmaterial.Rows[rowIndex].Cells[4].Value?.ToString() ?? "";
                    string unitName = dgvmaterial.Rows[rowIndex].Cells[6].Value?.ToString() ?? "";
                    
                    string details = $"物料编号: {materialNumber}\n" +
                                   $"物料名称: {materialName}\n" +
                                   $"规格型号: {specifications}\n" +
                                   $"单位名称: {unitName}";
                    
                    MessageBox.Show(details, "物料详情", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            };
            contextMenu.Items.Add(detailsItem);
            
            // 帮助菜单项
            ToolStripMenuItem helpItem = new ToolStripMenuItem("使用帮助");
            helpItem.Click += (sender, e) => ShowUsageTip();
            contextMenu.Items.Add(helpItem);
            
            // 将右键菜单绑定到DataGridView
            dgvmaterial.ContextMenuStrip = contextMenu;
        }

        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        private void Btnquxiao5_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        /// <summary>
        /// 初始化DataGridView，添加复选框列
        /// </summary>
        private void InitializeDataGridView()
        {
            // 清空现有列
            dgvmaterial.Columns.Clear();
            
            // 添加复选框列
            DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
            checkBoxColumn.HeaderText = "选择";
            checkBoxColumn.Name = "CheckBoxColumn";
            checkBoxColumn.Width = 50;
            checkBoxColumn.ToolTipText = "点击选择物料";
            dgvmaterial.Columns.Add(checkBoxColumn);
            
            // 添加物料ID列（隐藏列，用于数据绑定）
            DataGridViewTextBoxColumn materialIdColumn = new DataGridViewTextBoxColumn();
            materialIdColumn.HeaderText = "物料ID";
            materialIdColumn.Name = "MaterialIdColumn";
            materialIdColumn.DataPropertyName = "Id";
            materialIdColumn.Width = 80;
            materialIdColumn.Visible = false; // 隐藏此列
            dgvmaterial.Columns.Add(materialIdColumn);
            
            // 添加物料编号列
            DataGridViewTextBoxColumn materialNumberColumn = new DataGridViewTextBoxColumn();
            materialNumberColumn.HeaderText = "物料编号";
            materialNumberColumn.Name = "MaterialNumberColumn";
            materialNumberColumn.DataPropertyName = "MaterialNumber";
            materialNumberColumn.Width = 120;
            dgvmaterial.Columns.Add(materialNumberColumn);
            
            // 添加物料名称列
            DataGridViewTextBoxColumn materialNameColumn = new DataGridViewTextBoxColumn();
            materialNameColumn.HeaderText = "物料名称";
            materialNameColumn.Name = "MaterialNameColumn";
            materialNameColumn.DataPropertyName = "MaterialName";
            materialNameColumn.Width = 150;
            dgvmaterial.Columns.Add(materialNameColumn);
            
            // 添加规格型号列
            DataGridViewTextBoxColumn specificationsColumn = new DataGridViewTextBoxColumn();
            specificationsColumn.HeaderText = "规格型号";
            specificationsColumn.Name = "SpecificationsColumn";
            specificationsColumn.DataPropertyName = "Specifications";
            specificationsColumn.Width = 120;
            dgvmaterial.Columns.Add(specificationsColumn);
            
            // 添加单位ID列（隐藏列，用于数据绑定）
            DataGridViewTextBoxColumn unitIdColumn = new DataGridViewTextBoxColumn();
            unitIdColumn.HeaderText = "单位ID";
            unitIdColumn.Name = "UnitIdColumn";
            unitIdColumn.DataPropertyName = "Unit_Id";
            unitIdColumn.Width = 80;
            unitIdColumn.Visible = false; // 隐藏此列
            dgvmaterial.Columns.Add(unitIdColumn);
            
            // 添加单位名称列
            DataGridViewTextBoxColumn unitNameColumn = new DataGridViewTextBoxColumn();
            unitNameColumn.HeaderText = "单位名称";
            unitNameColumn.Name = "UnitNameColumn";
            unitNameColumn.DataPropertyName = "Unit_Name";
            unitNameColumn.Width = 100;
            dgvmaterial.Columns.Add(unitNameColumn);
            
            // 设置复选框列只能单选
            dgvmaterial.CellClick += Dgvmaterial_CellClick;
            
            // 添加双击行选择功能
            dgvmaterial.CellDoubleClick += Dgvmaterial_CellDoubleClick;
            
            // 设置DataGridView属性
            dgvmaterial.AllowUserToAddRows = false;
            dgvmaterial.AllowUserToDeleteRows = false;
            dgvmaterial.ReadOnly = true;
            dgvmaterial.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvmaterial.MultiSelect = false;
            
            // 添加右键菜单
            AddContextMenu();
        }

        /// <summary>
        /// DataGridView单元格点击事件，实现单选功能
        /// </summary>
        private void Dgvmaterial_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0 && e.RowIndex >= 0) // 点击复选框列
            {
                // 取消其他行的选中状态
                for (int i = 0; i < dgvmaterial.Rows.Count; i++)
                {
                    if (i != e.RowIndex)
                    {
                        dgvmaterial.Rows[i].Cells[0].Value = false;
                    }
                }
                
                // 设置当前行复选框状态
                bool currentValue = dgvmaterial.Rows[e.RowIndex].Cells[0].Value == null ? false : (bool)dgvmaterial.Rows[e.RowIndex].Cells[0].Value;
                dgvmaterial.Rows[e.RowIndex].Cells[0].Value = !currentValue;
                
                // 更新状态栏显示选中的物料信息
                UpdateStatusBar();
            }
        }
        
        /// <summary>
        /// DataGridView双击事件，快速选择物料
        /// </summary>
        private void Dgvmaterial_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex > 0) // 双击非复选框列
            {
                // 先选中当前行
                for (int i = 0; i < dgvmaterial.Rows.Count; i++)
                {
                    dgvmaterial.Rows[i].Cells[0].Value = (i == e.RowIndex);
                }
                
                // 自动点击确定按钮
                Btnsure5_Click(sender, e);
            }
        }

        private int PageIndex { get; set; } = 1;
        private int PageSize { get; set; } = 2;
        private int TotalCount { get; set; } = 0;
        private int TotalPages { get; set; } = 0;

        public class ApiResponse<T>
        {
            public int code { get; set; }
            public string message { get; set; }
            public string jwt { get; set; }
            public T pageData { get; set; }
            public T data { get; set; }
            public int totalCount { get; set; }
            public int totalPages { get; set; }
        }

        private ApiClient _apiClient;
        /// <summary>
        /// 显示物料信息
        /// </summary>
        /// <param name="customParams"></param>
        private async void GetData(Dictionary<string, string> customParams = null)
        {
            var parameters = new Dictionary<string, string>
                {
                    { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                };

            // 合并自定义参数（查询条件）
            if (customParams != null)
            {
                foreach (var kv in customParams)
                {
                    parameters[kv.Key] = kv.Value;
                }
            }
            var response = await _apiClient.GetAsync<ApiResponse<List<Material_TableOutput>>>(
                    endpoint: "Material/GetMaterTableShow",
                    parameters: parameters // 传递查询参数
                );
            // 处理响应结果
            if (response != null && response.code == 200)
            {
                // 将数据绑定到 DataGridView
                dgvmaterial.DataSource = response.pageData;
                
                // 初始化复选框列的值
                foreach (DataGridViewRow row in dgvmaterial.Rows)
                {
                    row.Cells[0].Value = false;
                }
                
                // 显示数据总数
                if (response.totalCount > 0)
                {
                    this.Text = $"选择物料 - 共 {response.totalCount} 条记录";
                }
                
                // 调试信息：显示列的数据属性名称
                Console.WriteLine($"列数量: {dgvmaterial.Columns.Count}");
                for (int i = 0; i < dgvmaterial.Columns.Count; i++)
                {
                    var col = dgvmaterial.Columns[i];
                    Console.WriteLine($"列 {i}: {col.Name} - {col.DataPropertyName} - {col.HeaderText}");
                }
            }
        }

        /// <summary>
        /// 物料查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnclick4_Click(object sender, EventArgs e)
        {
            var queryParams = new Dictionary<string, string>();

            //物料名称
            if (!string.IsNullOrWhiteSpace(tbxwuliaoname.Text))
            {
                queryParams["materialName"] = tbxwuliaoname.Text;
            }

            // 单元ID（从下拉框选的值）
            if (cbxunit.SelectedValue != null)
            {
                queryParams["unit_Id"] = ((int)cbxunit.SelectedValue).ToString();
            }

            GetData(queryParams);
        }

        /// <summary>
        /// 单位下拉框
        /// </summary>
        private async void LoadunitData()
        {
            try
            {
                // 示例：加载部门下拉框
                var deptResponse = await _apiClient.GetAsync<ApiResponse<List<UnitModel>>>(
                    endpoint: "Material/GetUnitModelShow");

                if (deptResponse != null && deptResponse.code == 200)
                {
                    // 清空并添加默认项
                    cbxunit.Items.Clear();
                    cbxunit.DisplayMember = "unitName";
                    cbxunit.ValueMember = "id";
                    cbxunit.DataSource = deptResponse.data;
                    cbxunit.SelectedIndex = -1;


                }


            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载下拉框数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
